/*:
* @plugindesc (v1.04)对象二级信息，按指定键或者点击切换。
* @author cnda2010 & 老饕
* @version 1.0.4(nswda)
* @date 4/20/2019
*
* @param KeyCode Test Mode
* @text 键盘测试模式
* @type boolean
* @on 启动
* @off 停用
* @desc 是否启动键盘测试模式，此模式下键盘按键后会显示该按键的编码，为下面的参数提供标准。
* @default false
*
* @param Secondary KeyCode
* @text 切换显示二级信息按键编码
* @type number
* @min 0
* @desc 切换二级显示的键盘按键编码，此编码可通过键盘测试模式得到需要的结果。默认取112【键盘F1】
* @default 112
*
* @param Default Show Text
* @text 默认显示二级信息
* @type boolean
* @on 显示二级信息
* @off 显示初始信息
* @default true
*
* @param Space Length
* @text 符号空格长度
* @type number
* @default 0
* @desc 数值转义符得到的数值中符号与数字之间的空格数量
*
* @param Need Change Scenes
* @text 允许切换的场景列表
* @type text[]
* @desc 允许切换的场景。
* @default ["Scene_Item","Scene_Skill","Scene_Equip","Scene_Battle","Scene_Shop"]
*
* @help
* 技能 物品 武器 装备标签
* <Secondary Text: text>
* 二级表述内容【固定】
* 表述内容支持转义符
* \n：换行符
* 可以通过转义符得到装备的数据库属性。
* \hp：装备的HP变化，带符号
* \hpabs：装备HP变化的绝对值
* \mp：装备的MP变化，带符号
* \mpabs：装备MP变化的绝对值
* \atk：装备攻击力，带符号
* \atkabs：装备攻击力绝对值
* \def：装备防御力，带符号
* \defabs：装备防御力绝对值
* \mat：装备魔法攻击，带符号
* \matabs：装备魔法攻击绝对	值
* \mdf：装备魔法防御，带符号
* \mdfabs：装备魔法防御绝对值
* \agi：装备敏捷，带符号
* \agiabs：装备敏捷绝对值
* \luk：装备幸运，带符号
* \lukabs：装备幸运绝对值
* 在使用CP_TPCore时，有以下转义符
* \tp：装备TP变化（对应于<TP Plus: x>标签的值），带符号
* \tpabs：装备TP变化的绝对值
* 
* 要显示一个反斜杠【\】需要输入4个反斜杠【\\\\】
* 上面所说的带符号，即当结果是非负数时数字前会有【+】，数字的正负号与
* 值之间有若干空格，空格长度由插件参数决定，默认为1。
* 【例】<Secondary Text: 攻击 \atk，魔攻 - \matabs。>
* 当物品攻击力为1， 魔法攻击为-2时会得到【攻击 + 1，魔攻 - 2。】
*
* <Secondary Text Eval>
* //JavaScript code
* text = "攻击 + 5  " + "防御 + 5。";
* </Secondary Text Eval> 
*
* 更新日志
* v1.00
* 插件完成
*
* v1.01
* 修复移动端点击文字不变化的问题。
*
* v1.02
* 固定文字标签支持转义字符\n以及YEP信息核心的部分转义符
* 允许自由设置切换文字的键盘按键
*
* v1.03
* 增加转义符读取装备的数据库数据。
*
* v1.04
* 数据转义符支持带符号。
* 支持自定义带符号数字中符号与数字之间的空格长度。
* 
* nswda
* 改为默认用“切换键（shift）”来切换说明。
*/

var Imported = Imported || {};
Imported.CP_ItemSecondaryInfo = true;

var params = PluginManager.parameters("CP_ItemSecondaryInfo");
var CP = CP || {};
CP.ItemInputManager = CP.ItemInputManager || {};

CP.ItemInputManager.KEY_KODE_TEST_MODE = eval(params["KeyCode Test Mode"]) || false;
CP.ItemInputManager.SECONDARY_KEY_KODE = Number(params["Secondary KeyCode"]) || 0;

CP.ItemInputManager.DEFAULT_SHOW_SECONDARY_TEXT = eval(params["Default Show Text"]);
CP.ItemInputManager.SPACE_LENGTH = Number(params["Space Length"]) || 0;
CP.ItemInputManager.NEED_CHANGE_SCENES = JSON.parse(params["Need Change Scenes"]);

for(var i = 0; i < CP.ItemInputManager.NEED_CHANGE_SCENES.length; i++){
	var string = CP.ItemInputManager.NEED_CHANGE_SCENES[i];
	CP.ItemInputManager.NEED_CHANGE_SCENES[i]= "scene instanceof " + string;
}

Input.keyMapper[CP.ItemInputManager.SECONDARY_KEY_KODE] = "F1";

CP.ItemInputManager.DATABASE_LOADED = DataManager.isDatabaseLoaded;
DataManager.isDatabaseLoaded = function(){
	if(!CP.ItemInputManager.DATABASE_LOADED.call(this))
		return false;

	CP.ItemInputManager.loadSecondaryData($dataSkills);
	CP.ItemInputManager.loadSecondaryData($dataItems);
	CP.ItemInputManager.loadSecondaryData($dataWeapons);
	CP.ItemInputManager.loadSecondaryData($dataArmors);

	return true;
};

CP.ItemInputManager.loadSecondaryData = function(dataArray){
	for(var i = 1; i < dataArray.length; i++){
		var item = dataArray[i];
		item.secondaryText = "";
		item.secondaryTextEval = null;
		if(item.meta["Secondary Text"]){
			var st = item.meta["Secondary Text"];
			item.secondaryText = st.trim();
		}

		if(item.meta["Secondary Text Eval"]){
			var reg = /<Secondary Text Eval>([\S\s]*)<\/Secondary Text Eval>/;
			reg.exec(item.note);
			item.secondaryTextEval = RegExp.$1;
		}
	}
};

CP.ItemInputManager.hasSecondaryText = function(item){
	if(!item)
		return false;
	if(!CP.ItemInputManager.getText(item))
		return false;
	return true;
};

CP.ItemInputManager.getText = function(item){
	var text = item.secondaryText || "";

	if(item.secondaryTextEval){
		try{
			eval(item.secondaryTextEval);
		}catch(e){
			console.log(e);
			text = item.secondaryText || "";
		}
	}

	if(text.trim() == "")
		text = null;

	return text;
};

CP.ItemInputManager.isNeedChangeText = function(){
	var scene = SceneManager._scene;
	for(var i = 0; i < CP.ItemInputManager.NEED_CHANGE_SCENES.length; i++){
		if(eval(CP.ItemInputManager.NEED_CHANGE_SCENES[i]))
			return true;
	}

	return false;
};

CP.ItemInputManager.getNumberString = function(value){
	if(typeof value !== "number")
		return value;
	var span = value < 0 ? "-" : "+";
	var space = "";
	for(var i = 0; i < this.SPACE_LENGTH; i++)
		space += " ";
	var number = String(Math.abs(value));

	return span + space + number;
};

//------------------------------
//  Input
//------------------------------
CP.ItemInputManager.ON_KEY_DOWN = Input._onKeyDown;
Input._onKeyDown = function(event){
	CP.ItemInputManager.ON_KEY_DOWN.call(this, event);

	if(CP.ItemInputManager.KEY_KODE_TEST_MODE)
		alert(event.keyCode);

	var name = Input.keyMapper[event.keyCode];
	//if(name === "F1")
	if(name === 'shift')
		this.onChangeShowText();
};

CP.ItemInputManager.UPDATE_GAMEPAD_STATE = Input._updateGamepadState;
Input._updateGamepadState = function(gamepad) {
	var lastState = this._gamepadStates[gamepad.index]|| [];
	CP.ItemInputManager.UPDATE_GAMEPAD_STATE.call(this, gamepad)
	var newState = this._gamepadStates[gamepad.index]
    for (var j = 0; j < newState.length; j++) {
        if (newState[j] !== lastState[j]) {
            var buttonName = this.gamepadMapper[j];
            if (buttonName) {
                this._currentState[buttonName] = newState[j];
				if(this._currentState['shift'])
					this.onChangeShowText();
            }
        }
    }
};
Input.onChangeShowText = function(){
	if(CP.ItemInputManager.isNeedChangeText())
		SceneManager._scene._helpWindow.onChangeShowText();
};

//------------------------------
//  Game_System
//------------------------------
CP.ItemInputManager.INIT_SYSTEM = Game_System.prototype.initialize;
Game_System.prototype.initialize = function(){
	CP.ItemInputManager.INIT_SYSTEM.call(this);

	this._showSecondaryData = CP.ItemInputManager.DEFAULT_SHOW_SECONDARY_TEXT;
};

Game_System.prototype.showSecondaryData = function(){
	if(!this._showSecondaryData)
		this._showSecondaryData = false;
	return this._showSecondaryData;
};

Game_System.prototype.setShowSecondaryData = function(show){
	this._showSecondaryData = show;
};

Game_System.prototype.changeShowSecondaryData = function(){
	this.setShowSecondaryData(!this.showSecondaryData());
};

//------------------------------
//  Window_Help
//------------------------------
CP.ItemInputManager.INIT_HELP_WINDOW = Window_Help.prototype.initialize;
Window_Help.prototype.initialize = function(numLines) {
    CP.ItemInputManager.INIT_HELP_WINDOW.call(this, numLines);

    this._item = null;
};

CP.ItemInputManager.SET_HELP_ITEM = Window_Help.prototype.setItem;
Window_Help.prototype.setItem = function(item) {
	CP.ItemInputManager.SET_HELP_ITEM.call(this, item);
	this._item = item;
	if(CP.ItemInputManager.hasSecondaryText(item) && (item.description.trim() === "" || $gameSystem.showSecondaryData())){
		var text = CP.ItemInputManager.getText(item);
		this.setText(this.convertEscapeCharactersForItemData(text, item));
	}
};

Window_Help.prototype.convertEscapeCharactersForItemData = function(text, item){
	text = this.addEnterCharacters(text);
	if(DataManager.isWeapon(item) || DataManager.isArmor(item))
		text = this.covertEquipDataCharacter(text, item);
	return Window_Base.prototype.convertEscapeCharacters.call(this, text);
};

Window_Help.prototype.addEnterCharacters = function(text){
	return text.replace(/\\n/g, "\n");
};

Window_Help.prototype.covertEquipDataCharacter = function(text, item){
	text = text.replace(/\\hpabs/g, this.paramHpAbs(item));
	text = text.replace(/\\hp/g, CP.ItemInputManager.getNumberString(this.paramHp(item)));
	text = text.replace(/\\mpabs/g, this.paramMpAbs(item));
	text = text.replace(/\\mp/g, CP.ItemInputManager.getNumberString(this.paramMp(item)));
	if(Imported.CP_TPCore){
		text = text.replace(/\\tpabs/g, this.paramTpAbs(item));
		text = text.replace(/\\tp/g, CP.ItemInputManager.getNumberString(this.paramTp(item))); 
	}
	text = text.replace(/\\atkabs/g, this.paramAtkAbs(item));
	text = text.replace(/\\atk/g, CP.ItemInputManager.getNumberString(this.paramAtk(item)));
	text = text.replace(/\\defabs/g, this.paramDefAbs(item));
	text = text.replace(/\\def/g, CP.ItemInputManager.getNumberString(this.paramDef(item)));
	text = text.replace(/\\matabs/g, this.paramMatAbs(item));
	text = text.replace(/\\mat/g, CP.ItemInputManager.getNumberString(this.paramMat(item)));
	text = text.replace(/\\mdfabs/g, this.paramMdfAbs(item));
	text = text.replace(/\\mdf/g, CP.ItemInputManager.getNumberString(this.paramMdf(item)));
	text = text.replace(/\\agiabs/g, this.paramAgiAbs(item));
	text = text.replace(/\\agi/g, CP.ItemInputManager.getNumberString(this.paramAgi(item)));
	text = text.replace(/\\lukabs/g, this.paramLukAbs(item));
	text = text.replace(/\\luk/g, CP.ItemInputManager.getNumberString(this.paramLuk(item)));
	return text;
};

Window_Help.prototype.paramValue = function(item, index){
	if(!item)
		return 0;
	return item.params[index];
};

Window_Help.prototype.paramHp = function(item){
	return this.paramValue(item, 0);
};

Window_Help.prototype.paramHpAbs = function(item){
	return Math.abs(this.paramHp(item));
};

Window_Help.prototype.paramMp = function(item){
	return this.paramValue(item, 1);
};

Window_Help.prototype.paramMpAbs = function(item){
	return Math.abs(this.paramMp(item));
};

Window_Help.prototype.paramTp = function(item){
	if(!item)
		return 0;
	return item.tpPlus;
};

Window_Help.prototype.paramTpAbs = function(item){
	return Math.abs(this.paramTp(item));
};

Window_Help.prototype.paramAtk = function(item){
	return this.paramValue(item, 2);
};

Window_Help.prototype.paramAtkAbs = function(item){
	return Math.abs(this.paramAtk(item));
};

Window_Help.prototype.paramDef = function(item){
	return this.paramValue(item, 3);
};

Window_Help.prototype.paramDefAbs = function(item){
	return Math.abs(this.paramDef(item));
};

Window_Help.prototype.paramMat = function(item){
	return this.paramValue(item, 4);
};

Window_Help.prototype.paramMatAbs = function(item){
	return Math.abs(this.paramMat(item));
};

Window_Help.prototype.paramMdf = function(item){
	return this.paramValue(item, 5);
};

Window_Help.prototype.paramMdfAbs = function(item){
	return Math.abs(this.paramMdf(item));
};

Window_Help.prototype.paramAgi = function(item){
	return this.paramValue(item, 6);
};

Window_Help.prototype.paramAgiAbs = function(item){
	return Math.abs(this.paramAgi(item));
};

Window_Help.prototype.paramLuk = function(item){
	return this.paramValue(item, 7);
};

Window_Help.prototype.paramLukAbs = function(item){
	return Math.abs(this.paramLuk(item));
};

Window_Help.prototype.isTouchedInsideFrame = function() {
    var x = this.canvasToLocalX(TouchInput.x);
    var y = this.canvasToLocalY(TouchInput.y);
    return x >= 0 && y >= 0 && x < this.width && y < this.height;
};

Window_Help.prototype.onTouch = function(){
	this.onChangeShowText();
};

Window_Help.prototype.onChangeShowText = function(){
	$gameSystem.changeShowSecondaryData();
	this.setItem(this._item);
	this.refresh();
};

Window_Help.prototype.processTouch = function() {
    if (this.isOpen() && CP.ItemInputManager.isNeedChangeText()) {
        if (TouchInput.isTriggered() && this.isTouchedInsideFrame()) {
            this.onTouch();
        }
    }
};

Window_Help.prototype.update = function(){
	Window_Base.prototype.update.call(this);

	this.processTouch();
};